#pragma once

//
// Helper class to manage Win32 event objects.
//
class CAutoResetEvent
{
public:
	HANDLE m_hEvent;		// handle to Win32 event object

	CAutoResetEvent(bool bInit = true, LPCWSTR pwszName = NULL)
	{
		m_hEvent = NULL;
		if(bInit)
			Init(pwszName);
	}

	~CAutoResetEvent()
	{
		if(m_hEvent != NULL)
			CloseHandle(m_hEvent);
	}

	bool Init(LPCWSTR pwszName = NULL)
	{
		if(m_hEvent == NULL)
			m_hEvent = CreateEvent(NULL, FALSE, FALSE, pwszName);
		return (m_hEvent != NULL);
	}

	void Set()
	{
		if(m_hEvent != NULL)
			SetEvent(m_hEvent);
	}

	DWORD Wait(DWORD dwTimeout = INFINITE)
	{
		if(m_hEvent == NULL)
			return ERROR_INVALID_HANDLE;
		return WaitForSingleObject(m_hEvent, dwTimeout);
	}
};